<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bind实现</title>
</head>

<body>
    <script>
        function testFun(...param) {
            console.log(this.name);
            console.log(param);
        }

        var zhangsan = {
            name: '张三',
        }

        var lisi = {
            name: '李四'
        }

        Function.prototype.myBind = function (thisObj, ...args) {
            var that = this
            let funToBind = function (...args2) {
                const isNew = this instanceof funToBind //this是否是funToBind的实例 也就是返回的fToBind是否通过new调用
                const context = isNew ? this : Object(thisObj) //new调用就绑定到this上,否则就绑定到传入的objThis上
                that.call(context, ...args, ...args2) // 用call调用源函数绑定this的指向并传递参数,返回执行结果
            }
            funToBind.prototype = Object.create(that.prototype) // 复制源函数的prototype给fToBind
            return funToBind // 返回拷贝的函数
        }

        var newFun = testFun.myBind(zhangsan, '这是参数')
        //var obj = new newFun(123)
        newFun(123)

        var oldFun = testFun.bind(zhangsan, '这是参数')
        new oldFun(123)
    </script>
</body>

</html>